<?php

namespace app\api\service\event;

use app\api\model\Account;
use app\api\model\cps\CpsFeed;
use app\api\model\cps\CpsJdFeed;
use app\api\model\cps\CpsMaterial;
use app\api\model\cps\CpsRecords;
use app\api\model\event\AccountToUser;
use app\api\model\event\Event;
use app\api\model\event\Integral;
use app\api\model\event\IntegralLog;
use app\api\model\event\Material;
use app\api\model\event\Merchant;
use app\api\model\event\MerchantLog;
use app\api\model\event\Order;
use app\api\model\event\Platform;
use app\api\model\event\PlatformValue;
use app\api\model\event\Product;
use app\api\model\event\Video;
use app\api\model\template\User;
use app\api\model\jd\User as UserEvent;
use app\api\service\template\TemplateService;
use app\api\service\token\LoginToken;
use app\lib\exception\event\OperationException;
use LinCmsTp5\admin\model\LinUser;
use phpDocumentor\Reflection\Types\False_;
use think\Db;
use think\Exception;

class OperationService
{
    private static $instance;

    public static function getInstance(): OperationService
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function getMerchantOrderList($params){
        $pageSize = $params['pageSize']??50;
        $order = Order::field("*")->json(['material_ids','data'])->with(['m_name','a_name','t_num','v_num']);
        if (isset($params['status'])){
            $order->where("status",$params['status']);
        }
        $list = $order->order("id desc")->paginate($pageSize)->each(function($item){
            # 总篇数
            $total_num = 0;
            # 图文总篇数
            $text_num = 0;
            # 视频总篇数
            $video_num = 0;
            foreach ($item->data as $v){
                $arr = (array)$v;
                $total_num+=$arr['num'];
                if ($arr['type'] == 1){
                    $text_num+=$arr['num'];
                }
                if ($arr['type'] == 2){
                    $video_num+=$arr['num'];
                }
            }
            $item->total_num = $total_num;
            $item->text_num = $text_num;
            $item->video_num = $video_num;
            # 已完成
            $item->complete_total_num = count($item->t_num) + count($item->v_num);
            $item->complete_text_num = count($item->t_num);
            $item->complete_video_num = count($item->v_num);
            # 单独平台已写篇数量
            $cr = CreatorService::getInstance();
            $platform_arr = $cr->platformArr($item->id);
            $item->platform_text = $platform_arr[0];
            $item->platform_video = $platform_arr[1];
            unset($item->t_num);
            unset($item->v_num);
            unset($platform_arr);

        });
        return $list;
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function checkOrder($params){
        $order = Order::where("id",$params['id'])->where("status",0)->findOrEmpty();
        if ($order->isEmpty()){
            throw new OperationException([
                'msg' => '审核订单不存在',
                'error_code' => 20001
            ]);
        }
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        DB::startTrans();
        try {
            $data = [
                "status"=>$params['status'],
                "reason"=>$params['reason']??null,
                "deliver_time"=>$params['deliver_time']??null
            ];
            if ($params['status'] == -1){
                #驳回并返回火箭豆
                $log = MerchantLog::where("order_id",$order['id'])->where("status",1)->find();
                Merchant::where("id",$order['merchant_id'])->setInc("balance",$log['balance']);
                $log_data = [
                    "order_id"=>$order['id'],
                    "balance"=>$log['balance'],
                    "merchant_id"=>$order['merchant_id'],
                    "content"=>"下单驳回并返回火箭豆",
                    "uid"=>$uid,
                    "type"=>1
                ];
                MerchantLog::create($log_data);
                #作废订单
                MerchantLog::where("order_id",$order['id'])->update(['status'=>"-1"]);
            }
            $order->save($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '审核订单变更失败',
                'error_code' => 20002
            ]);
        }
    }

    /**
     * @param $params
     * @throws OperationException
     */
    public function getAllocationList($params){
        $result = LinUser::field("id,username")->where('group_id',3)->select()->toArray();
        return $result;
    }

    /**
     * @param $params
     * @throws OperationException
     */
    public function Orderallocation($params){
        $order = Order::where("id",$params['id'])->findOrEmpty();
        if ($order->isEmpty()){
            throw new OperationException([
                'msg' => '订单不存在',
                'error_code' => 20001
            ]);
        }
        if (isset($order->author_id)){
            throw new OperationException([
                'msg' => '该订单执行人已分配',
                'error_code' => 20002
            ]);
        }

        DB::startTrans();
        try {
            $order->save($params);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '订单执行人分配失败',
                'error_code' => 20003
            ]);
        }
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function getMerchantProductList($params){
        $pageSize = $params['pageSize']??50;
        $product = Product::field('*');
        if (isset($params['status'])){
            $product->where("status",$params['status']);
        }
        $product->order('id desc');
        $list = $product->paginate($pageSize);
        return $list;
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function checkProduct($params){
        $product = Product::where("id",$params['id'])->findOrEmpty();
        if ($product->isEmpty()){
            throw new OperationException([
                'msg' => '商品不存在',
                'error_code' => 20001
            ]);
        }
        if ($product->status == 1){
            throw new OperationException([
                'msg' => '商品已审核过',
                'error_code' => 20002
            ]);
        }

        DB::startTrans();
        try {
            $data = [
                "status"=>$params['status'],
                "reason"=>$params['reason']??null
            ];
            $product->save($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '审核商品变更失败',
                'error_code' => 20003
            ]);
        }
    }

    /**
     * @throws OperationException
     */
    public function getPlatformList(){
        $data = PlatformValue::field("*")->select()->toArray();
        return $data;
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function getMerchantRegisterList($params){
        $pageSize = $params['pageSize']??50;
        $merchant = Merchant::field('*');
        if (!empty($params['phone'])){
            $merchant->whereLike("phone","%{$params['phone']}%");
        }

        $list = $merchant->order("id desc")->paginate($pageSize);
        return $list;
    }

    /**
     * @param $params
     * @throws OperationException
     */
    public function checkRegister($params){
        $merchant = Merchant::where("id",$params['id'])->where("status",0)->findOrEmpty();
        if ($merchant->isEmpty()){
            throw new OperationException([
                'msg' => '审核商户不存在',
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            $data = [
                "status"=>$params['status'],
                "reason"=>$params['reason']??null
            ];
            if ($params['status'] == 1){
                $user_data = [
                    "username"=>$merchant['account'],
                    "nickname"=>$merchant['account'],
                    "password"=>md5($merchant['password']),
                    "admin"=>1,
                    "active"=>1,
                    "group_id"=>5
                ];
                $user = LinUser::create($user_data);
                $data['uid'] = $user['id'];
            }
            $merchant->save($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '商户审核变更失败',
                'error_code' => 20002
            ]);
        }
    }

    /**
     * @param $params
     * @throws OperationException
     */
    public function assetChanges($params){
        $merchant = Merchant::where("id",$params['id'])->where("status",1)->findOrEmpty();
        if ($merchant->isEmpty()){
            throw new OperationException([
                'msg' => '商户不存在',
                'error_code' => 20001
            ]);
        }
        if ($params['type'] === 1){
            $msg = "账号充值";
        }else{
            $msg = "账号扣除";
        }
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        DB::startTrans();
        try {
            $log_data = [
                "merchant_id"=>$params['id'],
                "uid"=>$uid,
                "balance"=>$params['num'],
                "type"=>$params['type']
            ];
            if ($params['type'] == 1){
                $log_data['content'] = "增加火箭豆".$params['num'];
                $merchant->setInc('balance',$params['num']);
            }else{
                $log_data['content'] = "扣除火箭豆".$params['num'];
                $merchant->setDec('balance',$params['num']);
            }
            MerchantLog::create($log_data);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => $msg.'失败',
                'error_code' => 20002
            ]);
        }
        return $msg;
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function createMerchantMaterial($params){
        $order = Order::where("id",$params['order_id'])->json(['material_ids'])->findOrEmpty();
        if ($order->isEmpty()){
            throw new OperationException([
                'msg' => "订单不存在",
                'error_code' => 20001
            ]);
        }
        $material_ids = $order->material_ids;
        DB::startTrans();
        try {
            #追加素材
            foreach ($params['materials'] as $v){
                $data = [
                    "order_id"=>$order->id,
                    "url"=>$v['url'],
                    "type"=>$v['type']

                ];
                $material = Material::create($data);
                $material_ids[] = $material['id'];
            }
            #修改订单素材数组
            $order->save(['material_ids'=>$material_ids]);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => "订单新增素材失败",
                'error_code' => 20002
            ]);
        }


    }

    /**
     * @param $params
     * @throws OperationException
     */
    public function checkEvent($params){
        $event = Event::where("status",0)->where("id",$params['id'])->findOrEmpty();
        if ($event->isEmpty()){
            throw new OperationException([
                'msg' => "审核订单不存在",
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            $data = [
                "status"=>$params['status'],
                "reason"=>$params['reason']??null
            ];
            $event->save($data);
            # 审核通过推送模板


            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => "订单新增素材失败",
                'error_code' => 20002
            ]);
        }
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function updateOrderTags($params){
        $order = Order::where("id",$params['order_id'])->findOrEmpty();
        if ($order->isEmpty()){
            throw new OperationException([
                'msg' => "订单不存在",
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            $data = [
                "data"=>$params["data"]
            ];
            $order->save($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => "订单话题变更失败",
                'error_code' => 20002
            ]);
        }
    }

    /**
     * @param $params
     * @throws OperationException
     */
    public function updateOrderSummary($params){
        $order = Order::where("id",$params['order_id'])->findOrEmpty();
        if ($order->isEmpty()){
            throw new OperationException([
                'msg' => "订单不存在",
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            $data = [
                "summary"=>$params['summary']
            ];
            $order->save($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => "订单整体小结变更失败",
                'error_code' => 20002
            ]);
        }
    }

    /**
     * @param $params
     * @throws OperationException
     */
    public function checkBackfillUrl($params){

        $event = Event::where("id",$params['id'])->where("pub_type",2)->where("check",0)->findOrEmpty();
        if ($event->isEmpty()){
            throw new OperationException([
                'msg' => "审核文章不存在",
                'error_code' => 20001
            ]);
        }

        DB::startTrans();
        try {
            $info = [
                "check"=>$params['check'],
                "reason"=>$params['reason']??"驳回通知",
                "backfill_url"=>$params['backfill_url'],
                "feed_id"=>$params['feed_id']??""
            ];

            # 审核通过
            if ($params['check'] == 1){
               $uid = Account::where("app_id",$event->app_id)->value("uid");
               $integral = Integral::where("uid",$uid)->lock(true)->findOrEmpty();
               $integral->setInc("integral",2);
               IntegralLog::create(['uid'=>$uid,'event_id'=>$params['id']]);
            }else{
                $info['status'] = 1;
                # 驳回
                $u_info = Account::field("uid,pub_type")->where("app_id",$event->app_id)->find();
                $unionid = LinUser::where("id",$u_info['uid'])->value('unionid');
                if ($unionid){
                    $template = TemplateService::getInstance();
                    $openid = User::where("unionid",$unionid)->value("openid");
                    $data = [
                        "openid"=>[$openid],
                        "miniprogram"=>[
                            "appid"=>"wx343d841e87718665",
                            "pagepath"=>"pages/home/home"
                        ],
                        "data"=>[
                            "first"=>"",
                            "thing17"=> $event->title,
                            "short_thing5"=> "驳回通知",
                            "time15"=>date("Y年m月d日 H:i:s"),
                            "thing12"=>$info['reason']
                        ],
                        "template_id"=>'cy_LcH_ZWUZ-BGXzLRJrDwF4G616Ic1duL9j9pGa0D8',
                    ];
                    $template->pushTemplate($data);
                }
            }
            $event->save($info);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => "审核失败",
                'error_code' => 20002
            ]);
        }
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function getAccountList($params){
        $pageSize = $params['pageSize']??50;
        $in_use = $params['in_use']?? "全部";
        $leader = $params['leader']?? "全部";
        $account = Account::with(['platform','lin_user','account_to_user']);
        if (!empty($params['platform_id'])){
            $account->where("platform_id",$params['platform_id']);
        }
        if (!empty($params['username'])){
            $u_id = LinUser::where('username',$params['username'])->value('id');
            if (!empty($u_id)){
                $account->where('uid',$u_id);
            }
        }
        if (!empty($params['uid'])){
            $account->where("uid",$params['uid']);
        }
        if ($in_use == '1' || $in_use == '0'){
            $account->where('in_use',$in_use);
        }
        if ($leader != "全部"){
            $account->where("leader",$leader);
        }

        $res = $account->order("update_time desc")->paginate($pageSize);
        return $res;
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function getPlatform($params){
        $res = Platform::field('id,name')->select()->toArray();
        return $res;
    }

    /**
     * @param $params
     * @throws OperationException
     */
    public function getReleaseUser($params){
        $res = Db::table('lin_user')
            ->field("id,username")->where("group_id",4)->select()->toArray();
        return $res;
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function addAccount($params){
        $info = [
            "account"=>$params['account']??"",
            "password"=>$params['password']??"",
            "name"=>$params['name'],
            "app_id"=>$params['app_id'],
            "platform_id"=>$params['platform_id'],
            "remark"=>$params['remark']??null,
            "uid"=>$params['uid'],
            "pub_type"=>$params['pub_type']??2,
            "category"=>$params['category']??null,
            "home"=>$params['home'],
            "leader"=>$params['leader']??""
        ];
        $account = Account::where("app_id",$params['app_id'])->find();
        if ($account){
            throw new OperationException([
                'msg' => "渠道账号已存在，请勿重复提交",
                'error_code' => 20001
            ]);
        }
        DB::startTrans();
        try {
            Account::create($info);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => "添加失败",
                'error_code' => 20002
            ]);
        }

    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function upAccount($params){
        $info = [
            "account"=>$params['account']??"",
            "password"=>$params['password']??"",
            "name"=>$params['name'],
            "app_id"=>$params['app_id'],
            "platform_id"=>$params['platform_id'],
            "remark"=>$params['remark']??null,
            "uid"=>$params['uid'],
            "pub_type"=>$params['pub_type']??2,
            "category"=>$params['category']??null,
            "home"=>$params['home'],
            "in_use"=>$params['in_use']??0,
            "leader"=>$params['leader']??""
        ];

        $account = Account::where("id",$params['id'])->find();
        if (!$account){
            throw new OperationException([
                'msg' => "账号不存在",
                'error_code' => 20001
            ]);
        }

        if ($account['app_id'] != $params['app_id']){
            $new_account = Account::where("app_id",$params['app_id'])->findOrEmpty();
            if (!$new_account->isEmpty()){
                throw new OperationException([
                    'msg' => "渠道账号已存在，请勿重复提交",
                    'error_code' => 20002
                ]);
            }
        }

        DB::startTrans();
        try {
            $info['update_time'] = date("Y-m-d H:i:s");
            Account::where("id",$params['id'])->update($info);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => "更新失败",
                'error_code' => 20003
            ]);
        }
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function getOrderReport($params){
        # 查询指定订单下的对应app_id
        $app_id_query = Event::field('app_id')->where("order_id",$params['order_id']);
        if (!empty($params['start_time']) && !empty($params['end_time'])){
            $app_id_query->whereBetweenTime("create_time",$params['start_time'],$params['end_time']);
        }
        $app_id_arr = $app_id_query->group('app_id')->select()->toArray();
        $app_id = [];
        foreach ($app_id_arr as $val){
            $app_id[] = $val['app_id'];
        }
        # 查询app_id 分配的账号信息
        $account = Account::field("uid,GROUP_CONCAT(app_id SEPARATOR ',') AS app_id_arr")->with(['lin_user'])
            ->where("pub_type",2)->whereIn("app_id",$app_id)->group("uid")->select()->toArray();


        foreach ($account as $k=>$val){
            $app_id_arr = $val['app_id_arr'];
            # status= 3 and check=1 (回填通过审核) or status=3 and check=-1 (回填驳回)
            #  or status=3 and check=0(回填未审核) or status = 1 (未回填)
            $event = Event::field("status,check")->where("order_id",$params['order_id'])
                ->whereIn("app_id",$app_id_arr)->select()->toArray();

            $account[$k]['username'] = $val['lin_user']['username'];
            $account[$k]['total'] = 0; #全部
            $account[$k]['unclaimed'] = 0; # 待领取
            $account[$k]['success'] = 0; # 完成的
            $account[$k]['error'] = 0; # 驳回的
            $account[$k]['audit'] = 0; # 待审核的
            foreach ($event as $v){
                $account[$k]['total'] ++;
                if ($v['status'] == 1){
                    $account[$k]['unclaimed'] ++;
                }elseif ($v['status'] == 3 && $v['check'] == 1){
                    $account[$k]['success'] ++;
                }elseif ($v['status'] == 3 && $v['check'] == '-1'){
                    $account[$k]['error'] ++;
                }elseif ($v['status'] == 3 && $v['check'] == 0){
                    $account[$k]['audit'] ++;
                }
            }
            unset($account[$k]['lin_user']);
            unset($account[$k]['app_id_arr']);
            unset($account[$k]['uid']);
        }

        return $account;
    }


    /**
     * @param $params
     * @throws OperationException
     */
    public function setAccountCreator($params){
        DB::startTrans();
        try {
            AccountToUser::where("app_id",$params['app_id'])->delete();
            if (!empty($params['uids'])){
                # 清除
                $add = [];
                # 关联新增
                foreach ($params['uids'] as $v){
                    $add[] = [
                        "app_id"=>$params['app_id'],
                        "uid"=>$v,
                        "create_time"=>date("Y-m-d H:i:s")
                    ];
                }
                AccountToUser::insertAll($add);
            }
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => "设置失败",
                'error_code' => 20003
            ]);
        }
    }
    /**
     * @param $params
     * @throws OperationException
     */
    public function createtVideo($params){
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();
        $video = array($params["video_url"]);
        $video_history = json_encode($video);
        DB::startTrans();
        try {
            $exists = Video::where('video_url',$params["video_url"])->findOrEmpty();
            if($exists->isEmpty()){
                $data = [
                    "video_url"=>$params["video_url"],
                    "uid"=>$uid,
                    "cover"=>$params["cover"],
                    "title"=>$params["title"],
                    "video_history" => $video_history
                ];
                Video::create($data);
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '视频上传失败',
                'error_code' => 20002
            ]);
        }
    }

    /**
     * @param $params
     * @throws OperationException
     */
    public function getVideoList($params){
        $login = LoginToken::getInstance();
        $uid = $login->getCurrentUid();

        $pageSize = $params['pageSize']??50;
        if ($uid == 1 || $uid == 92){
            $videoList = Video::field("*")->order("id desc");
        }else{
            $videoList = Video::field("*")->where("uid",$uid)->order("id desc");
        }
        if (isset($params['status'])){
            if ($params['status'] != ''){
                $videoList->where('status',$params['status']);
            }
        }
        if (!empty($params['start_time']) && !empty($params['end_time'])){
            $videoList->whereBetweenTime("create_time",$params['start_time'],$params['end_time']);
        }

        $videoList = $videoList->with('name')->paginate($pageSize);
        return $videoList;
    }
    /**
     * @param $params
     * @throws OperationException
     */
    public function videoBack($params){
         $history = Video::where("id",$params["id"])->field("video_history")->find();
         $historyToArray = json_decode($history["video_history"],true);
         array_push($historyToArray,$params["video_url"]);
         $historyToJosn = json_encode($historyToArray);
        DB::startTrans();
        try {
            $data = [
                "video_url" => $params["video_url"],
                "video_history" => $historyToJosn,
                "status" => 0,
                "r_status" => 1,
                "reason" => "",
                "title" => $params["title"]
            ];
            Video::where("id",$params["id"])->update($data);
            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '视频上传失败',
                'error_code' => 20002
            ]);
        }

    }
    /**
     * @param $params
     * @throws OperationException
     */
    public function reset($params)
    {
        UserEvent::where("video_id", $params["id"])->update(["status" => 1]);
    }
    public function distributeList($params){
        $pageSize = $params['pageSize']??50;
        $list = UserEvent::field("*")->order("video_id desc");
        if (!empty($params['start_time']) && !empty($params['end_time'])){
            $list->whereBetweenTime("create_time",$params['start_time'],$params['end_time']);
        }
        if (isset($params['status'])){
            if ($params['status'] != ''){
                $list->where('status',$params['status']);
            }
        }
        $list = $list->with(['account','name'])->paginate($pageSize);
        return $list;
    }

    public function massUpload($params){
        DB::startTrans();
        try {
            #写入数据库
            foreach ($params["arr"] as $val) {
                $add = [
                    "link"=>$val,
//                    "title" => $val["title"],
//                    "topic"=>$val["topic"],
//                    "account"=>$val["account"],
//                    "tag" => $val["tag"],
//                    "genreTag"=>$val["genreTag"],
//                    "otherTag"=>$val["otherTag"]
                ];
                $exists = CpsMaterial::where('link',$val["link"])->findOrEmpty();
                if($exists->isEmpty()){
                    CpsMaterial::create($add);
                }
            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '导表失败',
                'error_code' => 20002
            ]);
        }
    }
    public function qnyUpload($params){
        DB::startTrans();
        try {
            #写入数据库
            $data = [
                "link"=>$params["link"]
            ];
            CpsMaterial::create($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '上传失败',
                'error_code' => 20002
            ]);
        }
    }
    public function collect($params){
        $pageSize = $params['pageSize']??50;
        $collect = Video::field("count(uid)as count,uid");
        if (!empty($params['start_time']) && !empty($params['end_time'])){
            $collect->whereBetweenTime("create_time",$params['start_time'],$params['end_time']);
        }
        if (isset($params['status'])){
            if ($params['status'] != ''){
                $collect->where('status',$params['status']);
            }
        }
        $collect = $collect->group("uid")->select()->toArray();
        foreach ($collect as $k=>$v){
            $info = LinUser::where("id",$v["uid"])->field("nickname")->find();
            $collect[$k]["nickname"] = $info["nickname"];
        }
        return $collect;
    }
    /**
     * @param $params
     * @throws OperationException
     */
    public function checkVideo($params,$type){
        switch ($type) {
            case "pass":
                $Data = [
                    "mark" => $params["mark"],
                    "status" => 1
                ];
                $msg = "通过失败";
                break;
            case "reject":
                $Data = [
                    "reason" => $params["reason"],
                    "reject_url" => $params["reject_url"],
                    "status" => -1
                ];
                $msg = "驳回失败";
                break;
            case "back":
                $back_url = "https://h5.m.jd.com/active/faxian/video/index.html?id=".$params["content_id"];
                $Data = [
                    "back_url" => $back_url,
                    "status" => 3,
                    "back_time" => date("YmdHis",time()),
                    "nid" => $params["content_id"]
                ];
                $msg = "回填失败";
                break;
        }
        try {
           if ($type == "back" || $type == "product"){
               UserEvent::where("video_id", $params["id"])->update($Data);
           }elseif ($type == "reject"){
               Video::where("id", $params["id"])->update($Data);
           }else{
               $data = Video::where('id', $params["id"])->field("*")->find();
               if (!is_array($params["tag1"]) || !is_array($params["tag2"]) || !is_array($params["tag3"])){
                   $params["tag1"] = array($params["tag1"]);
                   $params["tag2"] = array($params["tag2"]);
                   $params["tag3"] = array($params["tag3"]);
               }
               $info = [
                   "title" => $params["title"],
                   "video_url"=>$data["video_url"],
                   "uid"=>$data["uid"],
                   "product_url" => $params["product_url"],
                   "status" => 1,
                   "platform" => 'jd',
                   "pub_time" => $params["pub_time"],
                   "topic" => $params["topic"],
                   "video_id" => $data["id"],
                   "app_id" => $params["app_id"],
                   "type" => $params["type"],
                   "tag" => json_encode($params["tag1"],JSON_UNESCAPED_UNICODE),
                   "genreTag" => json_encode($params["tag2"],JSON_UNESCAPED_UNICODE),
                   "otherTag" => json_encode($params["tag3"],JSON_UNESCAPED_UNICODE)
               ];
               $Event = UserEvent::where('video_id',$params['id'])->findOrEmpty();
               if (!$Event->isEmpty()){
                   UserEvent::where("video_id",$params["id"])->update($info);
               }else{
                   UserEvent::create($info);
               }
               Video::where("id", $params["id"])->update($Data);
           }
        } catch (Exception $e) {
            throw new OperationException([
                'msg' => $msg,
                'error_code' => 20003
            ]);
        }
    }
    public function tDistribute($params){
        $current_time = date("Y-m-d H:i:s");
        $get_time = date("Y-m-d H:i:s", time() - 10);
        $result = [];
        $x = 0;

        DB::startTrans();
        $appids = [];
        $count = 0;
        try {
            $app_id__arr_query = CpsFeed::where("get_time",'>',$get_time);
//            if (!empty($params['type'])){
//                $app_id__arr_query->where("activity_name",$params['type']);
//            }
            $app_id_arr = $app_id__arr_query
                ->distinct(true)
                ->field('app_id')
                ->select()->toArray();
            $temporary = [];

            foreach ($app_id_arr as $val){
                $temporary[] = $val['app_id'];
            }
            $query = CpsFeed::where("status",1)
                ->where("pub_time", '<',$current_time)
                ->where("platform","TB")
                ->whereNotIn("app_id",$temporary);
//            if (!empty($params['type'])){
//                $query->where("activity_name",$params['type']);
//            }
            $list = $query->with(['account'])
                ->orderRand()
                ->lock(true)
                ->limit(10)->select()->toArray();
            if($list){
                $ids = [];
                foreach ($list as $item){
                    $result[] = $item;
                    $ids[] = $item['mid'];
                    $count++;
                }
                if (!empty($ids)){
                    CpsFeed::whereIn('mid',$ids)->update([
                        'status' => 2,
                        'get_time'=>date("Y-m-d H:i:s"),
                        'update_time'=>date("Y-m-d H:i:s")
                    ]);
                }

            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return $result;
    }

    public function jDistribute($params){
        $current_time = date("Y-m-d H:i:s");
        $get_time = date("Y-m-d H:i:s", time() - 10);
        $result = [];
        $x = 0;

        DB::startTrans();
        $appids = [];
        $count = 0;
        try {
            $app_id__arr_query = CpsJdFeed::where("get_time",'>',$get_time);
//            if (!empty($params['type'])){
//                $app_id__arr_query->where("activity_name",$params['type']);
//            }
            $app_id_arr = $app_id__arr_query
                ->distinct(true)
                ->field('app_id')
                ->select()->toArray();
            $temporary = [];

            foreach ($app_id_arr as $val){
                $temporary[] = $val['app_id'];
            }
            $query = CpsJdFeed::where("status",1)
                ->where("pub_time", '<',$current_time)
//                ->where("platform","JD")
                ->whereNotIn("app_id",$temporary);
//            if (!empty($params['type'])){
//                $query->where("activity_name",$params['type']);
//            }
            $list = $query->with(['account'])
                ->orderRand()
                ->lock(true)
                ->limit(10)->select()->toArray();
            if($list){
                $ids = [];
                foreach ($list as $item){
                        $result[] = $item;
                        $ids[] = $item['id'];
                        $count++;
                }
                if (!empty($ids)){
                    CpsJdFeed::whereIn('id',$ids)->update([
                        'status' => 2,
                        'get_time'=>date("Y-m-d H:i:s"),
                        'update_time'=>date("Y-m-d H:i:s")
                    ]);
                }

            }
            // 提交事务
            Db::commit();
        }catch (Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return $result;
    }

    public function jBackFillUrl($params){
        if (!empty($params["content_id"])){
            $back_url = "https://h5.m.jd.com/active/faxian/video/index.html?id=".$params["content_id"];
        }else{
            $back_url = $params["content_id"];
        }
        try {
            $data = [
                "back_time" => date("Y-m-d H:i:s"),
                "status" => $params["status"],
                "reason"=>$params["reason"],
                "back_url" =>$back_url
            ];
            CpsJdFeed::where("id",$params["id"])->update($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '回填失败',
                'error_code' => 20002
            ]);
        }
    }

    public function tBackFillUrl($params){
        if (!empty($params["content_id"])){
            $back_url = "https://creator.guanghe.taobao.com/page/unify/contentDetail?source=guanghe&contentId=".$params["content_id"]."&tab=1&mode=0&contentType=video";
        }else{
            $back_url = $params["content_id"];
        }
        try {
            $data = [
                "back_time" => date("Y-m-d H:i:s"),
                "status" => $params["status"],
                "reason"=>$params["reason"],
                "back_url" =>$back_url
            ];
            CpsFeed::where("mid",$params["id"])->update($data);
            // 提交事务
            Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '回填失败',
                'error_code' => 20002
            ]);
        }
    }

    public function materialList($params){
        $pageSize = $params['pageSize']??50;
        $list = CpsMaterial::field("*")->order("id desc");
        if (isset($params['status'])){
            if ($params['status'] != ''){
                $list->where('status',$params['status']);
            }
        }
        $list = $list->paginate($pageSize);
        return $list;
    }

    public function feedList($params){
        $pageSize = $params['pageSize']??50;
        $list = CpsFeed::field("*")->order("mid desc");
        if (isset($params['status'])){
            if ($params['status'] != ''){
                $list->where('status',$params['status']);
            }
        }
        $list = $list->paginate($pageSize);
        return $list;
    }

    public function cpsAdd($params){
//        $event = CpsFeed::where("link", $params["arr"][0]["link"])->findOrEmpty();
//        if (!$event->isEmpty()) {
//            throw new OperationException([
//                'msg' => '链接已提交过,请勿重新提交',
//                'error_code' => 20002
//            ]);
//        }
        Db::startTrans();
        try {
            foreach ($params["arr"] as $val){
                $data = [
                    "link" => $val["link"],
                    "type" => $val["type"],
                    "title" => $val["title"],
                    "platform"=>$val["platform"],
                    "content"=>empty($val["content"])?"":$val["content"],
                    "topic"=>$val["topic"],
                    "app_id"=>$val["account"],
                    "product_url"=>$val["product_url"],
                    "pub_time"=>$val["pub_time"]
                ];
                CpsFeed::create($data);
//            CpsMaterial::where("id",$params["id"])->update(["status"=>2]);
                Db::commit();
            }
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '通过失败',
                'error_code' => 20002
            ]);

        }
    }

    public function cpsReset($params){
        CpsFeed::where("mid", $params["id"])->update(["status" => 1]);
    }
    public function feedJdList($params){
        $pageSize = $params['pageSize']??50;
        $list = CpsJdFeed::field("*")->order("id desc");
        if (isset($params['status'])){
            if ($params['status'] != ''){
                $list->where('status',$params['status']);
            }
        }
        $list = $list->paginate($pageSize);
        return $list;
    }

    public function cpsJdReset($params){
        CpsJdFeed::where("id", $params["id"])->update(["status" => 1]);
    }

    public function cpsJdAdd($params){
        $event = CpsJdFeed::where("link", $params["link"])->findOrEmpty();
        if (!$event->isEmpty()) {
            throw new OperationException([
                'msg' => '链接已提交过,请勿重新提交',
                'error_code' => 20002
            ]);
        }
        $tag = [];
        $genreTag = [];
        $arrTag = explode("，",$params["tag"]);
        $arrGenreTag = explode("，",$params["genreTag"]);
        for ($i = 0; $i < count($arrTag); $i += 2) {
            $key1 = trim($arrTag[$i]);
            $value1 = trim($arrTag[$i + 1]);
            $pair1 = [
                "one" => $key1,
                "two" => $value1
            ];
            $tag[] = $pair1;
        }
        for ($i = 0; $i < count($arrGenreTag); $i += 2) {
            $key2 = trim($arrGenreTag[$i]);
            $value2 = trim($arrGenreTag[$i + 1]);
            $pair2 = [
                "one" => $key2,
                "two" => $value2
            ];
            $genreTag[] = $pair2;
        }
        $params["tag"] = json_encode($tag,JSON_UNESCAPED_UNICODE);
        $params["genreTag"] = json_encode($genreTag,JSON_UNESCAPED_UNICODE);

        Db::startTrans();
        try {
                $data = [
                    "link" => $params["link"],
                    "title" => $params["title"],
                    "topic"=>$params["topic"],
                    "app_id"=>$params["app_id"],
                    "top_intercept"=>$params["top_cut"],
                    "undercut"=>$params["under_cut"],
                    "tag"=>$params["tag"],
                    "genreTag"=>$params["genreTag"],
                    "product_url"=>$params["product_url"],
                    "pub_time"=>$params["pub_time"]
                ];
                CpsJdFeed::create($data);
                Db::commit();
        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '通过失败',
                'error_code' => 20002
            ]);

        }
    }
    public function getAccount($params){
        $account = Account::field("*")
            ->where("platform_id",12)
            ->where("cookie",'not null')
            ->whereNotIn("cookie","")
            ->select()
            ->toArray();
        return $account;
    }

    public function records($params){
        Db::startTrans();
        try {
            $data = [
                "jd_id"=>$params["jd_id"],
                "link"=>$params["link"],
                "title"=>$params["title"],
                "account_name"=>$params["account_name"],
                "date"=>$params["date"],
                "publish_time" => $params["publishTime"],
                "app_id"=>$params["app_id"],
                "vid"=>$params["vid"],
                "videoDuration"=>$params["videoDuration"],
                "status"=>$params["status"],
                "reason"=>$params["reason"]
            ];
            $event = CpsRecords::where("jd_id",$params["jd_id"])->where("date",$params["date"])->findOrEmpty();
            if ($event->isEmpty()){
                CpsRecords::create($data);
            }else{
                CpsRecords::where("date",$params["date"])
                    ->where("jd_id",$params["jd_id"])
                    ->update($data);
            }
            DB::commit();

        }catch (Exception $e){
            // 回滚事务
            Db::rollback();
            throw new OperationException([
                'msg' => '导入失败',
                'error_code' => 20002
            ]);
        }
        return $params["account_name"]." ".$params["date"]." ".$params["title"]."已采集完成";
    }
    public function list($params){
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        //每天每个账号的盈利情况
        $list = CpsRecords::field("*");
        if (!empty($params['start_date']) && !empty($params['end_date'])){
            $list->where("date","between",[$params['start_date'],$params['end_date']]);
        }else{
            $list->where("date",$yesterday);
        }
        $list = $list->select()->toArray();
        return $list;
    }
}
